<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="layout">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="产品" prop="product_ids">
            <el-select
              v-model="queryParams.product_ids"
              placeholder="请选择产品"
              filterable
              clearable
              multiple
              style="width: 150px;"
            >
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="业务类型" prop="recharge_type">
            <el-select
              v-model="queryParams.recharge_type"
              placeholder="业务类型"
              clearable
              style="width: 240px"
            >
              <!-- <el-option
                v-for="dict in dict.type.cz_product_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              /> -->
              <el-option label="话费" :value="1" />
              <el-option label="流量" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="运营商" prop="isp">
            <el-select
              v-model="queryParams.isp"
              placeholder="运营商"
              clearable
              style="width: 240px"
            >
              <!-- <el-option
                v-for="dict in dict.type.cz_isp"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              /> -->
              <el-option label="移动" :value="1" />
              <el-option label="联通" :value="2" />
              <el-option label="电信" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="省份" prop="province_id">
            <el-select
              v-model="queryParams.province_id"
              placeholder="省份"
              clearable
              filterable
              style="width: 240px"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.id"
                :label="province.short_name"
                :value="province.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="Search"
              size="small"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" size="small" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading"
          :data="dataList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="产品名称" align="center" prop="name" /> -->
          <el-table-column label="产品分类" align="center" prop="cate.name" />

          <el-table-column label="面值" align="center" prop="face_value" />
          <el-table-column label="原价" align="center" prop="market_price" />
          <el-table-column prop="type" label="业务类型" align="center">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.recharge_type == 1">
                话费</el-tag
              >
              <el-tag v-if="scope.row.recharge_type == 2"> 流量</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isp" label="运营商" align="center">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.isp == 1"> 移动</el-tag>
              <el-tag type="info" v-if="scope.row.isp == 2"> 联通</el-tag>
              <el-tag v-if="scope.row.isp == 3"> 电信</el-tag>
              <!-- <dict-tag
                :options="dict.type.cz_isp"
                :value="scope.row.product.isp"
              /> -->
            </template>
          </el-table-column>
          <el-table-column label="产品备注" align="center" prop="remark" />
          <el-table-column
            prop="channelProduct.channel_api_code"
            width="200"
            label="对接编码"
            align="center"
          >
            <template #default="scope">
              <el-popover
                placement="top"
                trigger="manual"
                :visible="scope.row.vlaueVisible"
                width="400"
              >
                <el-form @submit.prevent>
                  <el-form-item>
                    <el-input
                      :ref="'index' + scope.$index"
                      @keyup.enter="confrimDancy(scope.row, scope.$index)"
                      v-model="dancyValue"
                      placeholder="请输入产品编码"
                    ></el-input>
                  </el-form-item>
                  <el-form-item style="text-align: center">
                    <el-button
                      type="primary"
                      @click="confrimDancy(scope.row, scope.$index)"
                      >确定</el-button
                    >
                    <el-button
                      type="info"
                      @click="scope.row.vlaueVisible = !scope.row.vlaueVisible"
                      >取消</el-button
                    >
                  </el-form-item>
                </el-form>
                <template #reference>
                  <el-button
                    :type="scope.row.channel_api_code ? 'success' : 'info'"
                    @click="changeDaync(scope.row, scope.$index)"
                    >{{
                      scope.row.channel_api_code || customSpecDefault
                    }}</el-button
                  >
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column
            prop="channelProduct.is_defer"
            width="200"
            label="是否延迟"
            align="center"
          >
          <!-- v-model="scope.row.deferVisible" -->
          <template #default="scope">
              <el-popover
                placement="top"
                trigger="manual"
                
                :visible="scope.row.deferVisible"
                width="400"
              >
                <el-form @submit.native.prevent>
                  <el-form-item label="是否延迟回调" prop="is_defer">
                    <el-select
                      v-model="is_defer"
                      placeholder="是否延迟回调"
                      clearable
                      size="small"
                      style="width: 100%"
                    >
                      <!-- <el-option
                        v-for="dict in dict.type.is_defer"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      /> -->
                      <el-option
                        label="是"
                        :value="1"
                      />
                      <el-option
                        label="否"
                        :value="0"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item style="text-align: center">
                    <el-button
                      type="primary"
                      @click="confrimIsDefer(scope.row, scope.$index)"
                      >确定</el-button
                    >
                    <el-button
                      type="info"
                      @click="scope.row.deferVisible = !scope.row.deferVisible"
                      >取消</el-button
                    >
                  </el-form-item>
                </el-form>
                <template #reference>
                <el-button
                  :type="scope.row.is_defer == 1 ? 'success' : 'info'"
                  @click="changeDefer(scope.row, scope.$index)"
                  slot="reference"
                  >{{ getDeferText(scope.row.is_defer) || "否" }}</el-button
                >
              </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="layout">
        <el-form
          style="margin-top: 60px"
          :model="form"
          :rules="rules"
          ref="form"
          label-width="128px"
        >
          <el-form-item label="渠道商" prop="channel_id">
            <el-select
              filterable
              clearable
              v-model="form.channel_id"
              placeholder="请选择渠道商"
            >
              <el-option
                v-for="item in channelList"
                :key="item.id"
                :label="item.channel_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="折扣(原价)" prop="discount">
            <el-input-number
              v-model="form.discount"
              :precision="2"
              :step="1"
              :min="0"
              :max="100"
              placeholder="请输入折扣"
            ></el-input-number>
            <p>进价 = 原价 * 折扣 / 100，例如：100*92.5/100=92.5</p>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getList as listSpec,
  getListAll as listAllCzProduct,
} from "@/api/platform/czProductSpec";
import { getAllList as listAllCzCate } from "@/api/platform/czProductCate";

import { getArea2 as getArea} from "@/api/common";
import { addChannelProduct } from "@/api/channel/channelProduct";
import { getAllList as listAllChannel } from "@/api/channel";

export default {
  name: "rechargechanneladdProduct",
  //   dicts: ["product_status", "cz_isp", "cz_product_type"],
  data() {
    return {
      is_defer: null, // 弹出层标题
      layout: 12,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      multipleSelection: [],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品列表
      dataList: [],
      channelList: [],
      productList: [],
      // 省份列表
      provinceList: [],
      // 省份列表
      cityList: [],
      customSpecDefault: "empty", //产品编码的默认占位
      //临时存储的修改变量
      dancyValue: "",
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        id: undefined,
        isp: undefined,
        type: undefined,
        status: undefined,
        province_id: undefined,
        city_id: undefined,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        channel_id: [
          { required: true, message: "请选择渠道", trigger: "blur" },
        ],
        discount: [{ required: true, message: "请输入折扣", trigger: "blur" }],
      },
    };
  },
  created() {
    const screen = window.screen;
    if (screen.width < 500) {
      this.layout = 24;
    } else {
      this.layout = 12;
    }
    this.getList();
    this.getProvinceList();
    this.getAllProductList();
    this.getChannelList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listSpec(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log(response);
          this.dataList = response.data.items;
          this.total = response.data.total;
          this.dataList.forEach((item) => {
            item.vlaueVisible = false;
            // item.deferVisible = false;
            // this.$set(item, "vlaueVisible", false);
          });
          this.loading = false;
        }
      );
    },
    confrimIsDefer(item, index) {
      // if (this.is_defer===null) {
      //   this.$message.error("请选择");
      //   return false;
      // }
      item.is_defer = this.is_defer
      item.deferVisible = false
      // this.$set(item, "is_defer", this.is_defer);
      // this.$set(item, "deferVisible", false);
      // this.$forceUpdate();
    },
    getDeferText(value) {
      // let text = "否";
      // // console.log(this.dict.type.is_defer);
      // this.dict.type.is_defer.forEach((item) => {
      //   if (item.value == value) {
      //     text = item.label;
      //   }
      // });
      // return text;
      if(value==1){
        return "是"
      }else{
        return "否"

      }
    },
    changeDefer(item, index) {
      // console.log(6666666666);
      // 取消之前的
      this.dataList.forEach((item2) => {
        if (item2.vlaueVisible) {
          item2.deferVisible = false;
          // this.$set(item2, "deferVisible", false);
          // item2.vlaueVisible = false;
        }
      });
      // 重置dayncValue
      if (item.is_defer) {
        this.is_defer = item.is_defer;
      } else {
        this.is_defer = "";
      }
      item.deferVisible = true
      // this.$set(item, "deferVisible", true);
      // item.vlaueVisible = true;
      // 获取焦点
      // this.$nextTick(() => {
      //   this.$refs[`index${index}`].focus();
      // });
    },
    getAllProductList() {
      listAllCzCate().then((response) => {
        this.productList = response.data;
      });
    },
    getProvinceList() {
      this.loading = true;
      getArea({ level_type: 1 }).then((response) => {
        this.provinceList = response.data;
        this.loading = false;
      });
    },
    getCityList(id) {
      getArea({ level_type: 2, parent_id: id }).then((response) => {
        this.cityList = response.data;
      });
    },
    getChannelList() {
      listAllChannel().then((response) => {
        this.channelList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        channel_id: undefined,
        discount: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    confrimDancy(item, index) {
      if (!this.dancyValue) {
        this.$message.error("请输入产品编码");
        return false;
      }
      item.channel_api_code = this.dancyValue;
      item.vlaueVisible = false;
      this.$forceUpdate();
    },
    changeDaync(item, index) {
      // console.log(6666666666);
      // 取消之前的
      this.dataList.forEach((item2) => {
        if (item2.vlaueVisible) {
          item2.vlaueVisible = false;
          // item2.vlaueVisible = false;
        }
      });
      // 重置dayncValue
      if (item.channel_api_code) {
        this.dancyValue = item.channel_api_code;
      } else {
        this.dancyValue = "";
      }
      item.vlaueVisible = true;
      // 获取焦点
      this.$nextTick(() => {
        this.$refs[`index${index}`].focus();
      });
    },
    // 判断是否选规格并填写了产品编码
    validateChooiceSpec() {
      let validateRes = null;
      let errMsg = "";
      if (!this.multipleSelection.length) {
        errMsg = "请选择产品规格";
        validateRes = false;
        return { validateRes, errMsg };
      }
      // 检验产品编码
      validateRes = this.multipleSelection.every((item) => {
        errMsg = "对接编码不能为空";
        return (
          item.channel_api_code &&
          item.channel_api_code !== this.customSpecDefault
        );
      });
      return { validateRes, errMsg };
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const { validateRes, errMsg } = this.validateChooiceSpec();
          if (!validateRes) {
            this.$message.error(errMsg);
            return false;
          }
          const items = this.multipleSelection.map((item) => {
            return {
              is_defer: item.is_defer,
              channel_id: this.form.channel_id,
              cate_id: item.cate_id,
              spec_id: item.id,
              channel_api_code: item.channel_api_code,
              channel_price: (item.market_price * this.form.discount) / 100,
            };
          });
          addChannelProduct({ ...this.form, items }).then((response) => {
            this.$modal.msgSuccess("添加成功");
          });
        }
      });
    },
  },
};
</script>
